const {
	http
} = require("../../../utils/apiutils")
const app = getApp()
let ctxWidth = '';
let ctxHeight = '';
let ctx = null; //Camera
let canvaCtx = null; //canvas
var baidu = require('../../../utils/bdutils.js')

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		userInfo: {},
		isF: false,
		flash: false,
		isBaseImg: false,
		istak: 2,
		isSuccess: false,
		isca: false,
		idcard: {
			sex: "男",
			realName: "", //姓名
			nation: "", // 民族
			birthday: "", // 出生日期
			address: "", // 家庭住址
			idNumber: "", // 身份证号
			phone: ''
		},
		xieyi: false,
		popShow: false,
		popShow2: false,
		prizeName: '',
		hasIdNumber:false,
	},
	bindinputName: function (e) {
		console.log("-----------", e);
		this.data.idcard.realName = e.detail.value;
		// this.nextPush()
	},
	bindinputIdCard: function (e) {
		this.data.idcard.idNumber = e.detail.value;
		// this.nextPush()
	},
	bindinputMoblie: function (e) {
		this.data.idcard.sex = e.detail.value;
		// this.nextPush()
	},
	nextPush: function () {
		if (this.data.info.name.length > 0 && this.data.info.name.length < 20) {
			console.log("----姓名验证通过-")
			if (this.data.info.moblie.length == 11) {
				console.log("----手机号验证通过-")
				if (this.data.info.idcard.length > 10 && this.data.info.idcard.length < 20) {
					console.log("----身份证号验证通过-")
					this.setData({
						isF: true
					})
					return;
				}
			}
		}
		this.setData({
			isF: false,
		})

	},
	onclickSumbit: function () {
		if (!this.data.idcard.phone) {
			wx.showToast({
				title: '手机号不能为空',
				icon: "none"
			})
			return false;
		}
		if (!this.data.idcard.realName) {
			wx.showToast({
				title: '姓名不能为空',
				icon: "none"
			})
			return false;
		}
		if (!this.data.idcard.idNumber) {
			wx.showToast({
				title: '证件号不能为空',
				icon: "none"
			})
			return false;
		}
		// if (!this.data.xieyi) return;
		var that = this;
		wx.showLoading({
			title: '认证中...',
		})
		let params = JSON.parse(JSON.stringify(this.data.idcard));
		// params.inviteCode = getApp().globalData.inviteCode;
		if (params.idNumber.length == 15) {
			params.birthday = "19" + params.idNumber.substr(6, 6);
		} else if (params.idNumber.length == 18) {
			params.birthday = params.idNumber.substr(6, 8);
		}
		http.realName(params,
			function (res) {
				wx.hideLoading()
				if (res.status == 200) {
					wx.showToast({
						title: '认证成功',
						icon:"none"
					})
					getApp().globalData.userInfo.idNumber = that.data.idcard.idNumber
					getApp().globalData.userInfo.realName = that.data.idcard.realName
					that.getuser();
				} else {
					wx.showToast({
						title: res.msg,
						icon: "none",
					})
				}
			},
			function (err) {
				wx.hideLoading()
				wx.showToast({
					title: err,
					icon: "none",
				})
			})

		// }

	},
	//获取用户信息
	getuser: function () {

		var that = this;
		wx.showLoading({
			title: '加载中...',
		})
		http.userInfo({},
			function (res) {
				wx.hideLoading()
				console.log("------用户信息--", res);
				if (res.code == 0) {
					getApp().globalData.userInfo = res.data;
					wx.navigateBack({
						delta: 1,
					})
				} else {
					wx.showToast({
						title: res.message,
						icon: "none",
					})
				}
			},
			function (err) {
				wx.hideLoading()
			})

	},

	takePhoto1: function () {
		var that = this;
		baidu.getoAuthToken();
		wx.chooseImage({
			count: 1, // 最多可以选择的图片张数，默认9
			sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
			sourceType: ['album'], // album 从相册选图，camera 使用相机，默认二者都有
			success: function (res) {
				// success
				that.data.srcCanvasPath = res.tempFilePaths[0];
				that.confirmBack();
			},
			fail: function () {
				// fail
			},
			complete: function () {
				// complete
			}
		})
	},

	takePhoto() {
		console.log("--------生成照片-------")
		ctx = wx.createCameraContext(); //初始化camera
		ctx.takePhoto({ //生成图片
			quality: 'high',
			success: (res) => { //得到图片
				this.takeCanvas(res.tempImagePath)
				this.setData({
					baseImg: res.tempImagePath,
					// isBaseImg: true,
					isCanvas: true
				})
			}
		})
	},

	clearPhoto() {
		// canvaCtx.clearRect(0,0,ctxWidth, ctxHeight)
		// canvaCtx.draw()
		this.setData({
			srcCanvasPath: "",
			isCanvas: false,
			isSuccess: false,
			isBaseImg: false,
			isca: true,
		})
	},
	onShow() {
		this.changeText()
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		console.log(getCurrentPages())
		// let userInfo = getApp().globalData.userInfo;
		let userInfo = {};
		// this.setData({
		//   isca: true,
		//   istak: 1,
		// })
		// return
		if (userInfo.idNumber) {
			this.setData({
				istak: 3,
				userInfo: userInfo,
				isca: true,
				hasIdNumber: true,
				formWork:options.fromRoute=='work'?true:false
			})
		} else {
			this.setData({
				isca: true,
				hasIdNumber: false,
				formWork:options.fromRoute=='work'?true:false
			})
		}
	},
	confirmBack: function () {

		var base64 = 'data:image/jpg;base64,' + wx.getFileSystemManager().readFileSync(this.data.srcCanvasPath, "base64");
		// console.log("----", base64);
		var data = {
			image: base64,
			id_card_side: "front",
		}
		this.baiduUpdate(data)
	},
	baiduUpdate: function (data) {
		var that = this;
		baidu.sumbitImgToBadu(data,
			function (res) {
				console.log("----返回照片的信息---", res);
				if (res.image_status != "normal") {
					var str = "未知状态"
					if (res.image_status == "reversed_side") {
						str = "身份证正反面颠倒"
					} else if (res.image_status == "non_idcard") {
						str = "上传的图片中不包含身份证"
					} else if (res.image_status == "blurred") {
						str = "身份证模糊"
					} else if (res.image_status == "other_type_card") {
						str = "其他类型证照"
					} else if (res.image_status == "over_exposure") {
						str = "身份证关键字段反光或过曝"
					} else if (res.image_status == "other_type_card") {
						str = "其他类型证照"
					} else if (res.image_status == "over_dark") {
						str = "身份证欠曝（亮度过低）"
					} else {
						str = "未知错误"
					}
					wx.showModal({
						title: '识别错误',
						content: str,
						showCancel: false,
						confirmText: "我知道了",
						success(res) {
							that.clearPhoto()
						}
					})
					return;
				}
				if (res.words_result) {
					let w = res.words_result;
					var idNumber = "",
						name = "",
						nativePlace = "",
						nation = "",
						sex = "";
					if (w["公民身份号码"] && w["公民身份号码"].words != "") {
						idNumber = w["公民身份号码"].words;
					} else {
						wx.showModal({
							title: '识别错误',
							content: "未检查到身份证号",
							showCancel: false,
							confirmText: "我知道了",
							success(res) {
								that.clearPhoto()
							}
						})
						return;

					}
					if (w["姓名"] && w["姓名"].words != "") {
						name = w["姓名"].words;
					} else {
						wx.showModal({
							title: '识别错误',
							content: "未检查到姓名",
							showCancel: false,
							confirmText: "我知道了",
							success(res) {
								that.clearPhoto()
							}
						})
						return;

					}
					if (w["住址"] && w["住址"].words != "") {
						nativePlace = w["住址"].words;
					} else {
						wx.showModal({
							title: '识别错误',
							content: "未检查到住址",
							showCancel: false,
							confirmText: "我知道了",
							success(res) {
								that.clearPhoto()
							}
						})
						return;

					}
					if (w["民族"] && w["民族"].words != "") {
						nation = w["民族"].words;
					} else {
						wx.showModal({
							title: '识别错误',
							content: "未检查到民族",
							showCancel: false,
							confirmText: "我知道了",
							success(res) {
								that.clearPhoto()
							}
						})
						return;
					}
					if (w["性别"] && w["性别"].words != "") {
						sex = w["性别"].words;
					} else {
						wx.showModal({
							title: '识别错误',
							content: "未检查到性别",
							showCancel: false,
							confirmText: "我知道了",
							success(res) {
								that.clearPhoto()
							}
						})
						return;
					}

					var birthday = ""
					if (idNumber.length == 15) {
						birthday = "19" + idNumber.substr(6, 6);
					} else if (idNumber.length == 18) {
						birthday = idNumber.substr(6, 8);
					}
					var data = {
						sex: sex,
						realName: name, //姓名
						nation: nation, // 民族
						birthday: birthday, // 出生日期
						address: nativePlace, // 家庭住址
						idNumber: idNumber // 身份证号
					}
					wx.showToast({
						title: '识别成功请确认信息',
						icon: "none",
						success() {
							that.setData({
								istak: 2,
								idcard: {
									...that.data.idcard,
									...data
								},
							})
						}
					})
					console.log("----身份证信息-------", that.data.idcard);

				} else {
					wx.showModal({
						title: '识别错误',
						content: "身份认证失败",
						showCancel: false,
						confirmText: "我知道了",
						success(res) {
							that.clearPhoto()
						}
					})
				}
			},
			function (err) {
				wx.showToast({
					title: '身份认证失败',
					icon: "none",
				})
			})
	},
	takeCanvas(path) { //将拍摄的照片绘制到canvas上
		wx.getImageInfo({
			src: path,
			success: imgInfo => {
				let {
					info
				} = this.data;
				let prxHeight = (info.windowHeight - 150) / imgInfo.height; //计算设备比
				let prxWidth = info.windowWidth / imgInfo.width; //计算设备比
				let convasX = imgInfo.width / 15;
				let canvasWidth = convasX * 13;
				let canvasHeight = convasX * 13 * 3 / 5;
				let convasY = (imgInfo.height - canvasHeight) / 2;
				// let convasXL = convasX / 2;
				// 我这里宽度和高度都计算了设备比，其实两个值是一样的 ，计算一个就够了
				// ctx = wx.createCanvasContext("myCanvas", this);//自定义组件，需要加this
				canvaCtx = wx.createCanvasContext("myCanvas"); //自定义组件，需要加this
				// let a = (info.windowHeight - 150 - (info.windowWidth - 50) * 3 / 5) / 2
				console.log("-----------", imgInfo.width, imgInfo.height, convasX, convasY, canvasWidth, canvasHeight, prxWidth, prxHeight, (parseInt(canvasWidth) * prxWidth), (parseInt(canvasHeight) * prxHeight));
				canvaCtx.drawImage(path, convasX, convasY, canvasWidth, canvasHeight, 0, 0, canvasWidth * prxWidth, canvasHeight * prxHeight); //绘制到canvas上的位置，canvas的宽高等
				canvaCtx.draw(true, () => {
					wx.canvasToTempFilePath({
						fileType: "jpg",
						quality: 1,
						canvasId: "myCanvas",
						success: canvasToPath => {
							this.setData({
								// baseImg: canvasToPath.tempFilePath,
								srcCanvasPath: canvasToPath.tempFilePath,
								isBaseImg: true,
								isSuccess: true,
								isca: false,
								// isCanvas:false,
							})
						}
					})
					baidu.getoAuthToken();
					// wx.canvasToTempFilePath({
					//   fileType: "jpg",
					//   quality: 0.3,
					//   canvasId: "myCanvas",
					//   success: canvasToPath => {
					//     this.setData({
					//       isBaseImg: false,
					//       baseImg: canvasToPath.tempFilePath,
					//       srcCanvasPath: canvasToPath.tempFilePath
					//     })
					//   }
					// }, this)//自定义组件需要加this
				})
			}
		})
	},
	changeText() {
		wx.getSystemInfo({
			success: res => {
				this.setData({
					info: res,
				})
			}
		})
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},



	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {
		var shareObj = {
			title: "分享岗位", // 默认是小程序的名称(可以写slogan等)
			path: getApp().globalData.userInfo.inviteCode ? '/pages/index/index?code=' + getApp().globalData.userInfo.inviteCode : '/pages/index/index', // 
			imageUrl: '',
			success: function (res) {
				// 转发成功之后的回调
				if (res.errMsg == 'shareAppMessage:ok') {}
			}
		}
		console.log("------------", shareObj);
		// 返回shareObj
		return shareObj;
	},
	choose() {
		this.setData({
			istak: 1
		})
	},
	onChange(e) {
		this.setData({
			xieyi: e.detail
		})
	},
	toxieyi() {
		wx.navigateTo({
			url: '../xieyi/xieyi'
		})
	},
	hidePop() {
		this.setData({
		  popShow: false,
		  popShow2: false,
		})
		if (this.data.formWork) {
			let route = getCurrentPages();
			route[route.length - 2].onclickNext();
		} else { 
			wx.navigateBack({
				delta: 1,
			})
		}
		
	  },
	getPhone(e) {
		let key = e.currentTarget.dataset.key;
		console.log(e)
		if (e.detail.errMsg != "getPhoneNumber:ok") {
			wx.showToast({
				title: '您拒绝授权，将不能使用小程序功能',
				icon: "none"
			})
			return false;
		}
		let params = {
			...e.detail,
			openid: getApp().globalData.openid,
			unionid: getApp().globalData.unionid || getApp().globalData.userInfo.unionid,
		}
		wx.showLoading({
			mask: true
		})
		let _this = this;
		http.getUserPhone(params, (res) => {
			wx.hideLoading()
			_this.setData({
				['idcard.phone']: res,
				hasIdNumber:true
			})
			if (key == 1) {
				_this.choose()
			} 
		}, err => {
			wx.hideLoading()
			wx.showToast({
				icon: "none",
				title: '获取失败，请重新获取',
			})
		})
	}
})